package com.boot.common.message;

import com.boot.common.utils.BeanUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @author Cheng JiYe
 * @description:
 * @date 2020/10/2 18:54
 */
public class BaseService {
    /**
     * 日志记录器
     */
    protected Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 启用分页
     *
     * @param req 分页请求头
     */
    public static void startPage(RequestPageHead req) {
        if (req.isPage()) {
            startPage(req.getPageNum(), req.getPageSize());
        }
    }

    /**
     * 启用分页
     *
     * @param pageNum  当前页码
     * @param pageSize 每页数量
     */
    public static void startPage(int pageNum, int pageSize) {
        if (pageNum < 1) {
            throw new RuntimeException("The page number must not be less than 0!");
        }
        if (pageSize < 1) {
            throw new RuntimeException("The number of rows per page must not be less than 0!");
        }

        PageHelper.startPage(pageNum, pageSize);
    }

    /**
     * 封装分页结果集
     *
     * @param <T>
     * @param list 数据列表
     * @return
     */
    public static <T> ResultPage<List<T>> packPageResult(List<T> list) {
        ResultPage<List<T>> result = new ResultPage<>();
        packPageInfo(result, list);
        result.setData(list);
        result.setCode(200);
        result.setMsg("操作成功");
        return result;
    }

    /**
     * 封装分页结果集
     *
     * @param <T>
     * @param list 数据列表
     * @return
     */
    public static <T> ResultPage<T> packPageResult(T data, List list) {
        ResultPage<T> result = new ResultPage<>();
        packPageInfo(result, list);
        result.setData(data);
        result.setCode(200);
        result.setMsg("操作成功");
        return result;
    }

    /**
     * 封装分页的基础信息
     *
     * @param resultPage
     * @param pageInfoList
     */
    public static void packPageInfo(ResultPage<?> resultPage, List<?> pageInfoList) {
        PageInfo<?> pageInfo = new PageInfo<>(pageInfoList);
        resultPage.setCurrentPage(pageInfo.getPageNum());
        resultPage.setPages(pageInfo.getPages());
        resultPage.setPageSize(pageInfo.getPageSize());
        resultPage.setTotal((int) pageInfo.getTotal());
    }


    /**
     * 将类的List转换为另一个类的List
     *
     * @param origList  源对象List
     * @param destClass 目标对象Class
     */
    public static <T> List<T> convertBeanList(List<?> origList, Class<T> destClass) {
        List<T> destList = BeanUtils.convertBeanList(origList, destClass);
        return destList;
    }

}
